//
//  PSFilterPlayerNonFirstHandMove.m
//  PrefCore
//
//  Created by Sergey on 6/20/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSFilter.h"

PSHandHash PSFilterPlayerNonFirstHandMove(
    PSHandHash candidates
,   PSPlayerId player
,   PSTrickHash trick
,   PSCardSuit trump
,   uint8_t handIndex
) {
    // We should get here only if the player is not a first hand
    assert(handIndex != 0);
    PSCardSuit trickSuit = PSTrickCardSuit(trick);
    assert(trickSuit != kSuitNone);
    BOOL hasTrickSuit = PSHandGetSuit(candidates, trickSuit) != 0;
    BOOL hasTrump = PSHandGetSuit(candidates, trump) != 0;
    // Remember current highest card in the trick
    PSCard *highest = PSTrickHighestCard(trick, trump);
    PSHandHash res = 0;
    for (int i = 0 ; i != PS_CARD_SUIT_RISING_LEN ; i++) {
        PSCardSuit s = PSCardSuitRising[i];
        PSCardRankSet set = PSHandGetSuit(candidates, s);
        if (set == 0) {
            continue;
        }
        if (s != trickSuit && (hasTrickSuit || (s != trump && hasTrump))) {
            continue;
        }
        // Simulate player move with the highest card in this suit
        trick = PSTrickAddCardPlayer(trick, player, [PSCard cardWithSuit:s andRank:PSCardSetHighestRank(set)].compressed);
        // Get new highest card in the trick
        PSCard *newHighest = PSTrickHighestCard(trick, trump);
        // If the highest card has been changed return all candidates as a player might win the trick
        if (highest != newHighest) {
            return candidates;
        }
        // The highest card has not been changed - add only the lowest card of this suit as candidate
        res = PSHandAddCard(res, [PSCard cardWithSuit:s andRank:PSCardSetLowestRank(set)]);
        // Restore trick
        trick = PSTrickRemoveLastCard(trick);
    }
    return res != 0 ? res : candidates;
}
